package com.qf.producer.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerMain {
    public static void main(String[] args) throws IOException, TimeoutException {
        //构建一个连接工厂(配置和rabbitmq的连接信息)
        ConnectionFactory factory = new ConnectionFactory();
        //设置rabbitmq的机器ip
        factory.setHost("localhost");
        //设置rabbitmq运行的端口
        factory.setPort(5672);
        //设置登录用户名
        factory.setUsername("guest");
        //设置登录密码
        factory.setPassword("guest");
        //设置写入数据的虚拟主机
        factory.setVirtualHost("cdm");

        //获取Connection对象
        Connection conn = factory.newConnection();
        //获取channel
        Channel channel = conn.createChannel();

        //利用channel发送消息
        //① 声明一个队列
        channel.queueDeclare("work.que",true,false,false,null);

        //② 向队列中发送消息
        for (int i = 0; i < 10; i++) {
            channel.basicPublish("","work.que",null,("第"+i+"条rabbitmq消息").getBytes(StandardCharsets.UTF_8));
        }

        //释放资源
        channel.close();
        conn.close();
    }
}
